package com.canyou.redmine.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.canyou.redmine.R;
import com.canyou.redmine.adapter.ProjectIssueAdapter;
import com.canyou.redmine.model.Issue;
import com.canyou.redmine.model.IssuePage;
import com.canyou.redmine.model.Member;
import com.canyou.redmine.model.MemberPage;
import com.canyou.redmine.model.TimeEntries;
import com.canyou.redmine.model.TimeEntriesPage;
import com.canyou.redmine.network.CanYouAPI;
import com.canyou.redmine.ui.base.BaseActivity;
import com.canyou.redmine.util.CanYouLog;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.loopj.android.http.TextHttpResponseHandler;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

/**
 * 项目详情
 *
 * @author admin
 */
public class ProjectActivity extends BaseActivity {
    private int projectId;
    private String projectName;

    private TextView tvManagers;
    private TextView tvDevelopsers;
    private TextView tvTesters;

    private LinearLayout llDevelopers;
    private LinearLayout llTesters;

    private TextView tvTimeEntries;

    private RefreshLayout refreshLayout;
    private RecyclerView rvIssues;
    private ProjectIssueAdapter adapter;
    private List<Issue> issueList = new ArrayList<>();
    Bundle bundle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_project);
        bundle = getIntent().getExtras();
        projectId = bundle.getInt("projectId", 0);
        projectName = bundle.getString("projectName", "");

        initUI();
    }

    private void initUI() {
        setBackButton(true);
        setTitle(projectName);

        tvManagers = findViewById(R.id.tv_managers);
        tvDevelopsers = findViewById(R.id.tv_developers);
        tvTesters = findViewById(R.id.tv_testers);

        llDevelopers = findViewById(R.id.ll_developers);
        llTesters = findViewById(R.id.ll_testers);

        tvTimeEntries = findViewById(R.id.tv_time_entries);
        refreshLayout = findViewById(R.id.refreshLayout);
        refreshLayout.setRefreshHeader(new ClassicsHeader(this));
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                getIssuesByProjectId(projectId);
            }
        });
        rvIssues = findViewById(R.id.rv_issues);
        rvIssues.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
        adapter = new ProjectIssueAdapter(this, R.layout.list_item_project_issue, issueList);
        rvIssues.setAdapter(adapter);
        rvIssues.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent = new Intent(getApplicationContext(), IssueActivity.class);
                Issue issue = issueList.get(position);
                intent.putExtra("issue", JSON.toJSONString(issue));
                startActivity(intent);
            }
        });
        getMembers(projectId);
    }

    private void updateMemberLayout(List<Member> members) {
        StringBuffer managers = new StringBuffer();
        StringBuffer developers = new StringBuffer();
        StringBuffer testers = new StringBuffer();

        for (Member member : members) {
            String name = member.getUser().getName();
            String roleName = member.getRoles().get(0).getName();
            if ("Manager".equals(roleName)) {
                managers.append(name).append(",");
            } else if ("Developer".equals(roleName)) {
                developers.append(name).append(",");
            } else if ("Tester".equals(roleName)) {
                testers.append(name).append(",");
            }
        }

        tvManagers.setText(managers);

        if (TextUtils.isEmpty(developers)) {
            llDevelopers.setVisibility(View.GONE);
        } else {
            llDevelopers.setVisibility(View.VISIBLE);
            tvDevelopsers.setText(developers);
        }

        if (TextUtils.isEmpty(testers)) {
            llTesters.setVisibility(View.GONE);
        } else {
            llTesters.setVisibility(View.VISIBLE);
            tvTesters.setText(testers);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        refreshLayout.autoRefresh();
        getTimeEntries(projectId);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.add, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_add:
                startActivity(new Intent(this, NewIssueActivity.class).putExtras(bundle));
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private void getMembers(int projectId) {
        CanYouAPI.getMembersByProjectId(projectId, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                CanYouLog.e(responseString);
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {

                MemberPage page = JSON.parseObject(responseString, MemberPage.class);
                List<Member> members = page.getMemberships();

                updateMemberLayout(members);

                CanYouLog.i(responseString);

            }
        });
    }

    private void getTimeEntries(int projectId) {
        CanYouAPI.getTimeEntriesByProjectId(projectId, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {

            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {

                TimeEntriesPage page = JSON.parseObject(responseString, TimeEntriesPage.class);

                List<TimeEntries> list = page.getTime_entries();

                float total = 0;
                for (TimeEntries item : list) {
                    total += item.getHours();
                }

                tvTimeEntries.setText(getString(R.string.project_time_entries, total));
            }
        });
    }

    private void getIssuesByProjectId(int projectId) {
        CanYouAPI.getIssuesByProjectId(projectId, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {

            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {

                IssuePage page = JSON.parseObject(responseString, IssuePage.class);
                List<Issue> data = page.getIssues();
                issueList.clear();
                issueList.addAll(data);
                adapter.notifyDataSetChanged();
                refreshLayout.finishRefresh();
            }
        });
    }
}
